#!/usr/bin/env python
#-*- coding:utf-8 -*-

import httplib2
import urlparse
import simplejson as json
import os

from oauth2client.client import OAuth2WebServerFlow

class auth2KB(object):
    def __init__(self):
        self.redirect_uri='urn:ietf:wg:oauth:2.0:oob'
        self.flow = OAuth2WebServerFlow(client_id='7ce7a9e9435566dbb30f04bbc6b83d12',
                                       client_secret='0a998eb5d8411c3c206425bac2a5d48c',
                                       auth_uri = 'https://auth.kanbox.com/0/auth',
                                       token_uri = 'https://auth.kanbox.com/0/token',
                                       scope='',
                                       redirect_uri=self.redirect_uri) 
                                       
        self.auth_code = None
        self.http_auth = None
                                       
    def getAuth2Uri(self):
        '''
        Get authroize URL
        build a auth code request uri
        '''
        return self.flow.step1_get_authorize_url()
        
    def getAuthCodeFromUri(self, uri):
        '''
        Get auth code from redirect uri 
        After send auth code request uri, get user auth code from the uri
        '''
        #print self.redirect_uri+'?'
        if uri.find(self.redirect_uri+'?')!=-1:
            pos = uri.find('code')
            self.auth_code = uri[pos+5:]
            print urlparse.urlparse(uri)
            print urlparse.parse_qsl(uri)
            print urlparse.parse_qs(uri)
        else:
            self.auth_code = None
        return self.auth_code
    
    def build(self):
        '''
        Get an authorized http object, through this object, we can talk with
        the server
        '''
        if self.auth_code != None:
            credentials = self.flow.step2_exchange(self.auth_code)
            print credentials
            self.http_auth = credentials.authorize(httplib2.Http())
            print self.http_auth
            return True
        else:
            return False
            
    def getUserInfo(self):
        '''
        Get user info
        '''
        if self.http_auth != None:
            resp, content = self.http_auth.request('https://api.kanbox.com/0/info')
            print resp
            print content
            return json.loads(content)
        else:
            return None
            
    def getUserFileList(self, path = None, shash = None):
        '''
        Get File List
        '''
        if self.http_auth != None:
            if shash != None:
                shash = '?hash=' + shash
            url = urlparse.urljoin('https://api.kanbox.com/0/list', path)
            url = urlparse.urljoin(url, shash)
            print url        
            resp, content = self.http_auth.request(url)
            print resp
            print content
            return json.loads(content)
        else:
            return None
    
    def synUserFile(self, home = None, path = None, direction = 'down'):
        '''
        synchronize file
        '''            
        if self.http_auth != None:
            if direction == 'down': # download
                print home
                print path
                if not os.path.exists(home):
                    print "home path is invalid"
                    return None
                #if not os.path.exists(path):
                #    print "path is invalid"
                #    return None
                if home[-1:] == '/':
                    home = home[:-1] + path
                else:
                    home = home + path
                url = 'https://api.kanbox.com/0/download'             
                url += path
                print url
                resp, content = self.http_auth.request(url)
                if resp['status'] == '200':
                    with open(home, "wb") as f:
                        f.write(content)
                #return json.loads(content)
                return 'OK'
            else: # upload
                pass
        else:
            return None
